package com.gzpi.hwgggh.config;

import com.gzpi.hwgggh.utils.HwggConstants;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;

/**
 * @date : 2020-12-31 17:31
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${save.file.path}")
    private String saveFilePath;

    @Bean(name="multipartResolver")
    public MultipartResolver multipartResolver(){
        return new CommonsMultipartResolver();
    }

    /**
     * 事务管理
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("=============================================");
        File f = null;
        String path = saveFilePath;
//        try {
//            f = new File(ResourceUtils.getURL("classpath:").getPath());
//            path=f.getAbsolutePath();
//            path=path.substring(0,path.indexOf("webapps")-1);
//            path=path.substring(0,path.lastIndexOf(File.separator)+1);
//            System.out.println(path);
//        } catch (FileNotFoundException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        if (!(path.endsWith("/") || path.endsWith(File.separator))) path+=File.separator;
        HwggConstants.resetNewPath("file:///"+path, path.substring(path.indexOf("/")+1)); //设置文件保存路径
        File   file=new File(HwggConstants.SAVE_PATH.substring("file:///".length()));
        if(!file.exists()) {//是否存在保存文件路径
            file.mkdirs(); //新建文件路径
        }

        registry.addResourceHandler("/"+HwggConstants.MAPPING_PATH+"**")//回显地址
                .addResourceLocations(HwggConstants.SAVE_PATH);//上传地址
    }
}
